import { getSetting, chooseAddress, openSetting, showModal ,showToast} from "../../utils/asyncWx.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
import {request} from "../../request/index.js"
Page({
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },
  onShow() {
    // 1 获取缓存中的收货地址信息
    const address = wx.getStorageSync("address");
    console.log(address);
    // 1 获取缓存中的购物车数据
    let cart = wx.getStorageSync("cart") || [];
    // 过滤后的数组
    cart =cart.filter(v =>v.checked)
    this.setData({address})
    // this.setCart(checkedCart)
    // 1 总价格 总数量
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      // 计算
        totalPrice += v.num * v.data.message.goods_price;
        totalNum += v.num;
    })
    // 赋值
    this.setData({
      cart,totalPrice,totalNum,address
    })
    
    wx.setStorageSync("cart", cart);
  },
  // 点击按钮支付事件
 async handleOrderPay(){
    // 1.判断缓存中是否有token
    const token =wx.getStorageSync("token")
    // 2.判断
    if (!token) {
      wx.navigateTo({
        url: '/pages/auth/index',
      })
      return;
    }
    // 3.创建订单
    // 请求头参数
    const header ={Authorization:token} 
    // 请求体参数 -订单总价格
    const order_price =this.data.totalPrice
    // 请求体参数 -收货地址
    const consignee_addr =this.data.address.all
    // 获取购物车
    const cart=this.data.cart
    // 对象数组
    let goods =[]
    cart.forEach(v=>goods.push({
      goods_id:v.goods_id,
      goods_number:v.num,
      goods_price:v.goods_price
    }))
    // 封装
    const orderP ={order_price,consignee_addr,goods}
    // 发送请求创建订单
    const {order_number} =await request({url:"/my/orders/create",method:"POST",data:orderP,header})
    console.log(order_number);
    
  }
})